package com.mobile.check.activitys;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.droidlover.xdroidmvp.cache.SharedPref;
import cn.droidlover.xdroidmvp.imageloader.ILFactory;
import cn.droidlover.xdroidmvp.kit.Kits;
import cn.droidlover.xdroidmvp.kit.NLog;
import cn.droidlover.xdroidmvp.kit.NToast;
import cn.droidlover.xdroidmvp.mvp.XActivity;

import com.mobile.check.beans.TaskItemInfo;
import com.mobile.check.app.R;
import com.mobile.check.db.EntityManager;
import com.mobile.check.present.TaskItemCheckPresent;
import com.mobile.check.bluetooth.BluetoothSppClient;
import com.mobile.check.dialogs.BottomItem;
import com.mobile.check.dialogs.BottomListDialog;
import com.mobile.check.dialogs.CheckTipDialog;
import com.mobile.check.util.AppContents;
import com.mobile.check.views.MyNoBgTextView;
import com.mobile.check.views.MyTextView;
import com.mobile.check.views.SubmitTipDialog;

/**
 * 类名: TaskItemDetailActivity
 * 作者: 李学伟
 * 日期: 2020年10月13日 21:46
 * 描述:
 */
public class TaskItemCheckActivity extends XActivity<TaskItemCheckPresent> {
    @BindView(R.id.deviceTv)
    MyTextView deviceTv;
    @BindView(R.id.areaTv)
    MyTextView areaTv;
    @BindView(R.id.equipmentTv)
    MyTextView equipmentTv;
    @BindView(R.id.itemLabelTv)
    MyTextView itemLabelTv;
    @BindView(R.id.locationDescTv)
    MyTextView locationDescTv;
    @BindView(R.id.assemblyTypeTv)
    MyTextView assemblyTypeTv;
    @BindView(R.id.assemblyChildTypeTv)
    MyTextView assemblyChildTypeTv;
    @BindView(R.id.leakValueTv)
    MyTextView leakValueTv;
    @BindView(R.id.stoptimeTv)
    MyTextView stoptimeTv;
    @BindView(R.id.testDeviceTv)
    MyTextView testDeviceTv;
    @BindView(R.id.testDateTv)
    MyTextView testDateTv;
    @BindView(R.id.testValueTv)
    MyTextView testValueTv;
    @BindView(R.id.repeatTestValueTv)
    MyTextView repeatTestValueTv;
    @BindView(R.id.isLeakTv)
    MyTextView isLeakTv;
    @BindView(R.id.leakLocationTv)
    MyTextView leakLocationTv;
    @BindView(R.id.indoorTv)
    MyTextView indoorTv;
    @BindView(R.id.leakSpeedTv)
    MyTextView leakSpeedTv;
    @BindView(R.id.testPathTv)
    MyTextView testPathTv;
    @BindView(R.id.testPicTv)
    MyTextView testPicTv;
    @BindView(R.id.descTv)
    MyTextView descTv;
    @BindView(R.id.backgroundTv)
    MyTextView backgroundTv;
    @BindView(R.id.testPersonTv)
    MyTextView testPersonTv;
    @BindView(R.id.statusIv)
    ImageView statusIv;
    @BindView(R.id.saveBtn)
    TextView saveBtn;

    Long parentId;
    int index;
    int taskType;
    boolean isLocalTask;
    @BindView(R.id.showPicTv)
    TextView showPicTv;

    TaskItemInfo targetItemInfo;
    @BindView(R.id.repeatPersonTv)
    MyNoBgTextView repeatPersonTv;
    @BindView(R.id.repeatDeviceTv)
    MyNoBgTextView repeatDeviceTv;
    @BindView(R.id.repeatDateTv)
    MyNoBgTextView repeatDateTv;

    @BindView(R.id.selectLeakLocationTv)
    TextView selectLeakLocationTv;
    String backGroudValueMark;
    boolean mbThreadStop = false;
    protected BluetoothSppClient mBSC = null;
    int minStopTime;

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        mBSC = GlobalPoolApplication.instance.mBSC;
    }

    @Override
    public void initView() {
        super.initView();
        titleTv.setText("检测");
        if (taskType == 0) {
            repeatTestValueTv.setVisibility(View.GONE);
            repeatDateTv.setVisibility(View.GONE);
            repeatDeviceTv.setVisibility(View.GONE);
            repeatPersonTv.setVisibility(View.GONE);
            statusIv.setImageResource(R.drawable.hadchecked);
        } else if (taskType == 1) {
            selectLeakLocationTv.setVisibility(View.GONE);
            testPersonTv.setVisibility(View.GONE);
            testDeviceTv.setVisibility(View.GONE);
            testDateTv.setVisibility(View.GONE);
            testValueTv.setLabelColor(getResources().getColor(R.color.color3675bd));
            testDateTv.setLabelColor(getResources().getColor(R.color.color3675bd));
            statusIv.setImageResource(R.drawable.fujian);
        } else if (taskType == 2) {
            selectLeakLocationTv.setVisibility(View.GONE);
            repeatTestValueTv.setVisibility(View.GONE);
            repeatDateTv.setVisibility(View.GONE);
            repeatDeviceTv.setVisibility(View.GONE);
            repeatPersonTv.setVisibility(View.GONE);
            statusIv.setImageResource(R.drawable.hadchecked);
        }
    }

    @Override
    public void getDataFromServer() {
        getP().getTaskItemInfos(parentId, index);
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_taskitemdetail;
    }

    @Override
    public void getIntentData() {
        parentId = getIntent().getLongExtra("parentId", 0l);
        index = getIntent().getIntExtra("index", 0);
        taskType = getIntent().getIntExtra("taskType", 0);
        isLocalTask = getIntent().getBooleanExtra("isLocalTask", true);
    }

    @Override
    public TaskItemCheckPresent newP() {
        return new TaskItemCheckPresent();
    }

    public static void lunch(Context context, Long parentId, int index, int taskType, boolean isLocalTask) {
        Intent intent = new Intent(context, TaskItemCheckActivity.class);
        intent.putExtra("parentId", parentId);
        intent.putExtra("index", index);
        intent.putExtra("taskType", taskType);
        intent.putExtra("isLocalTask", isLocalTask);
        context.startActivity(intent);
    }

    public void getTaskItemDetialSuccess(TaskItemInfo info) {
        saveBtn.setClickable(false);
        saveBtn.setTextColor(getResources().getColor(R.color.gruy));
        NLog.d(TAG, "info = " + info.toString());
        targetItemInfo = info;
        backGroudValueMark = "back_" + targetItemInfo.getTaskName();
        deviceTv.setValue(info.getDevice());
        areaTv.setValue(info.getArea());
        equipmentTv.setValue(info.getEquipment());
        itemLabelTv.setValue(info.getLabel());
        locationDescTv.setValue(info.getLocationDesc());
        assemblyTypeTv.setValue(info.getAssemblyType());
        assemblyChildTypeTv.setValue(info.getAssemblyChildType());
        leakValueTv.setValue(info.getLeakValue());
        String stopTime = info.getMinStopTime();
        if (TextUtils.isEmpty(stopTime)) {
            stoptimeTv.setValue("0");
        } else {
            stoptimeTv.setValue(stopTime);
        }

        String isLeak = info.getIsLeak();
        if (TextUtils.equals("1", isLeak)) {
            isLeak = "是";
            leakLocationTv.setValue(info.getLeakLocation());
        } else if (TextUtils.equals("0", isLeak)) {
            isLeak = "否";
            leakLocationTv.setValue("");
        }
        isLeakTv.setValue(isLeak);


        String indoor = info.getIndoor();
        if (TextUtils.equals("1", indoor)) {
            indoor = "是";
        } else if (TextUtils.equals("0", indoor)) {
            indoor = "否";
        }
        indoorTv.setValue(indoor);
        leakSpeedTv.setValue(info.getLeakSpeed());
        testPathTv.setValue(info.getTestPath());
        testPicTv.setValue(info.getTestPic());
        descTv.setValue(info.getDesc());
        String backGround = info.getBackGround();
        if (TextUtils.isEmpty(backGround) || TextUtils.equals("0", backGround)) {
            backGround = SharedPref.getInstance(this).getString(backGroudValueMark, "0");
        }
        backgroundTv.setValue(backGround);
        titleTv.setText(info.getLabel());


        if (info.isHadTest()) {
            statusIv.setVisibility(View.VISIBLE);
        } else {
            statusIv.setVisibility(View.INVISIBLE);
        }

        switch (taskType) {
            case 0:
                if (TextUtils.equals("是", info.getIsLeak()) || TextUtils.equals("1", info.getIsLeak())) {
                    leakLocationTv.setLabelColor(R.color.red);
                }
            case 2:
                if (info.isHadTest()) {
                    testPersonTv.setValue(info.getTestPerson());
                    testDeviceTv.setValue(info.getTestDevice());
                    testDateTv.setValue(info.getTestDate());
                    testValueTv.setValue(info.getTestValue());
                } else {
                    testPersonTv.setValue("");
                    testDeviceTv.setValue("");
                    testDateTv.setValue("");
                    testValueTv.setValue("");
                }
                break;
            case 1:
                testPersonTv.setValue(info.getTestPerson());
                testDeviceTv.setValue(info.getTestDevice());
                testDateTv.setValue(info.getTestDate());
                testValueTv.setValue(info.getTestValue());
                if (info.isHadTest()) {
                    repeatPersonTv.setValue(info.getRepeatPerson());
                    repeatDeviceTv.setValue(info.getRepeatDevice());
                    repeatDateTv.setValue(info.getRepeatDate());
                    repeatTestValueTv.setValue(info.getRepeatValue());
                } else {
                    repeatPersonTv.setValue("");
                    repeatDeviceTv.setValue("");
                    repeatDateTv.setValue("");
                    repeatTestValueTv.setValue("");
                }
                break;
        }
        hadTest = false;
    }

    @OnClick({R.id.upBtn, R.id.testBtn, R.id.saveBtn, R.id.backgroundBtn, R.id.nextBtn, R.id.showPicTv, R.id.selectLeakLocationTv})
    public void onViewClicked(View view) {

        switch (view.getId()) {
            case R.id.upBtn:
                checkTest(-1);

                break;
            case R.id.testBtn:
                String background = backgroundTv.getValue();
                if (TextUtils.isEmpty(background) || TextUtils.equals(background, "0")) {
                    showToast("请先检测背景值");
                } else {
                    startTest();
                }
                break;
            case R.id.saveBtn:
                save(1);
                break;
            case R.id.backgroundBtn:
                CheckBackgroundActivity.lunch(this, backGroudValueMark);
                break;
            case R.id.selectLeakLocationTv:
                showPhotoBottomDialog();
                break;
            case R.id.nextBtn:
                checkTest(1);
                break;
            case R.id.showPicTv:
                showPic();
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case 0x002:
                String backgroundValue = data.getStringExtra("backgroundValue");
                backgroundTv.setValue(backgroundValue);
                break;
            case 0x003:
                String device = data.getStringExtra("value");
                SharedPref.getInstance(this).put(AppContents.TESTDEVICE, device);
                testDeviceTv.setValue(device);
                break;
            case 0x004:
                String name = data.getStringExtra("value");
                SharedPref.getInstance(this).put(AppContents.USERNAME, name);
                testPersonTv.setValue(name);
                break;
        }
    }

    private void save(int type) {
        String testuser = SharedPref.getInstance(this).getString(AppContents.USERNAME, "");
        String testDeviceTvValue = SharedPref.getInstance(this).getString(AppContents.TESTDEVICE, "");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/M/dd HH:mm:ss");


        String testDate = dateFormat.format(Calendar.getInstance().getTimeInMillis());
        String background = backgroundTv.getValue();
        if (TextUtils.isEmpty(background) || TextUtils.equals(background, "0")) {
            showToast("背景值未检测");
            return;
        } else {
            SharedPref.getInstance(this).putString(backGroudValueMark, background);
        }
        String testVaue;
        String leakLocation = leakLocationTv.getValue();
        if (TextUtils.isEmpty(leakLocation) && TextUtils.equals("1", targetItemInfo.getIsLeak())) {
            showToast("请选择泄漏点位置");
            return;
        }
        targetItemInfo.setLeakLocation(leakLocation);
        switch (taskType) {
            case 0:
            case 2:
                testVaue = testValueTv.getValue();
                if (TextUtils.isEmpty(testVaue)) {
                    showToast("请检测后保存");
                    return;
                }
                targetItemInfo.setTestPerson(testuser);
                targetItemInfo.setTestDate(testDate);
                targetItemInfo.setTestValue(testVaue);
                targetItemInfo.setBackGround(background);
                targetItemInfo.setTestDevice(testDeviceTvValue);
                break;
            case 1:
                testVaue = repeatTestValueTv.getValue();
                if (TextUtils.isEmpty(testVaue)) {
                    showToast("请检测后保存");
                    return;
                }
                targetItemInfo.setRepeatDate(testDate);
                targetItemInfo.setRepeatPerson(testuser);
                targetItemInfo.setRepeatValue(testVaue);
                targetItemInfo.setRepeatDevice(testDeviceTvValue);
                targetItemInfo.setBackGround(background);
                break;

        }


        getP().save3(targetItemInfo, taskType, type);
    }

    protected void showPhotoBottomDialog() {
        List<BottomItem> list = getP().getLeakLocation();
        BottomListDialog bottomListDialog = new BottomListDialog(this, new BottomListDialog.BottomListSelectListener<String>() {
            @Override
            public void itemClickCallback(String selectStr) {
                leakLocationTv.setValue(selectStr);
            }
        });
        bottomListDialog.disPlay(list);
    }

    CheckTipDialog checkTipDialog;

    private void startTest() {

        boolean isConnect = GlobalPoolApplication.instance.isConnect();

        if (!isConnect) {
            NToast.shortToast(this, "当前设备未连接");
        } else {
            String minStopTime = targetItemInfo.getMinStopTime();
            int waitTime;
            try {
                waitTime = Integer.parseInt(minStopTime);
            } catch (Exception e) {
                waitTime = 20;
            }
            checkTipDialog = new CheckTipDialog(this, new CheckTipDialog.SlectClickListener() {
                @Override
                public void submitClick(String maxValue) {
                    mbThreadStop = true;
                    if (!TextUtils.isEmpty(maxValue)) {
                        setTestValues(maxValue);
                    }
                }

            });
            checkTipDialog.display(waitTime);
            if (AppContents.ISTEST) {
                return;
            }
            new receiveTask().executeOnExecutor(GlobalPoolApplication.instance.FULL_TASK_EXECUTOR);

        }

    }

    boolean hadTest;

    private void setTestValues(String testValue) {
        saveBtn.setClickable(true);
        saveBtn.setTextColor(getResources().getColor(R.color.white));
        hadTest = true;
        switch (taskType) {
            case 0:
            case 2:
                testValueTv.setValue(testValue);
                testPersonTv.setValue(SharedPref.getInstance(this).getString(AppContents.USERNAME, ""));
                testDeviceTv.setValue(SharedPref.getInstance(this).getString(AppContents.TESTDEVICE, ""));
                testDateTv.setValue(Kits.Date.getYmdhms2(Calendar.getInstance().getTimeInMillis()));
                break;
            case 1:
                repeatTestValueTv.setValue(testValue);
                repeatPersonTv.setValue(SharedPref.getInstance(this).getString(AppContents.USERNAME, ""));
                repeatDeviceTv.setValue(SharedPref.getInstance(this).getString(AppContents.TESTDEVICE, ""));
                repeatDateTv.setValue(Kits.Date.getYmdhms2(Calendar.getInstance().getTimeInMillis()));
                break;

        }

        String background = backgroundTv.getValue();
        String leekValue = targetItemInfo.getLeakValue();

        float testValuef = getP().getFloat(testValue);
        float leekValuef = getP().getFloat(leekValue);
        float backgroundf = getP().getFloat(background);

        if (testValuef > leekValuef) {
            isLeakTv.setValue("是");
            targetItemInfo.setIsLeak("1");
            showPhotoBottomDialog();
        } else {
            isLeakTv.setValue("否");
            targetItemInfo.setIsLeak("0");
        }
    }

    @Override
    public void onBackPressed() {
        checkTest(0);
    }

    @Override
    public void onLeftBtnClick(View view) {
        checkTest(0);
    }

    private void checkTest(int type) {
        if (hadTest) {
            showTip(type);
        } else {
            dealCheckResult(type);
        }
    }

    private void showTip(final int type) {
        SubmitTipDialog submitTipDialog = new SubmitTipDialog(this, new SubmitTipDialog.SlectClickListener() {
            @Override
            public void submitClick() {
                save(type);
            }

            @Override
            public void cancelClick() {
                dealCheckResult(type);
            }
        });
        submitTipDialog.display("温馨提示", "您刚刚进行的检测还没有保存。是否保存", "不保存", "保存");
    }

    private void dealCheckResult(int type) {
        if (type == 0) {
            finish();
        } else if (type == -1) {
            if (index == 0) {
                NToast.shortToast(this, "没有上一个了");
            } else {
                index--;
                getP().getTaskItemInfos(parentId, index);
            }
        } else if (type == 1) {
            if (index >= getP().getTaskItemInfoSize(parentId) - 1) {
                NToast.shortToast(this, "没有下一个了");
            } else {
                index++;
                getP().getTaskItemInfos(parentId, index);
            }
        }
    }

    public void saveSuccess(int type) {
        showToast("保存成功");
        targetItemInfo.setIsHadTest(true);
        EntityManager.getInstance().saveTaskItemInfo(targetItemInfo);
        disLoadDialog();
        dealCheckResult(type);

    }


    @Override
    public boolean isNotWorkConnect() {
        return false;
    }


    private void showPic() {
        String sRoot = Environment.getExternalStorageDirectory().getPath();// 获取跟目录
        String picDir = isLocalTask ? "本地任务" : "网络任务";
        String picPath = sRoot.concat("/").concat("检测系统") + File.separator
                + picDir + File.separator
                + "图片"
                + File.separator
                + targetItemInfo.getTestPic();
        File f = new File(picPath); // 获取文件句柄
        if (null == f || !f.exists() || !f.isFile()) {
            NToast.shortToast(this, "无对应图片信息");
            return;
        }
        final Dialog dia = new Dialog(this, R.style.dialogFullscreen);
        dia.setContentView(R.layout.img_show);

        ImageView imageView = (ImageView) dia.findViewById(R.id.img);
        // 选择true的话点击其他地方可以使dialog消失，为false的话不会消失
        dia.setCanceledOnTouchOutside(true); // Sets whether this dialog is
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dia.dismiss();
            }
        });
        dia.show();
        ILFactory.getLoader().loadFile(imageView, f, null);
    }


    @Override
    protected void onDestroy() {
        mbThreadStop = true;
        getP().onDestory();
        super.onDestroy();
    }

    /*多线程处理(建立蓝牙设备的串行通信连接)*/
    private class receiveTask extends AsyncTask<String, String, Integer> {
        /**
         * Constant: the connection is lost
         */
        private final static byte CONNECT_LOST = 0x01;
        /**
         * Constant: the end of the thread task
         */
        private final static byte THREAD_END = 0x02;

        /**
         * 线程启动初始化操作
         */
        @Override
        public void onPreExecute() {
            mbThreadStop = false;
        }

        /**
         * 线程异步处理
         */
        @Override
        protected Integer doInBackground(String... arg0) {
            mBSC.Receive(); //首次启动调用一次以启动接收线程
            while (!mbThreadStop) {
                if (!mBSC.isConnect())//检查连接是否丢失
                    return (int) CONNECT_LOST;

                if (mBSC.getReceiveBufLen() > 0) {
                    SystemClock.sleep(20); //先延迟让缓冲区填满
                    this.publishProgress(mBSC.Receive());
                }
                NLog.d("receiveTask", TAG + "接收数据");
            }
            return (int) THREAD_END;
        }

        /**
         * 线程内更新处理
         */
        @Override
        public void onProgressUpdate(String... progress) {
            if (null != progress[0]) {
                String value = progress[0].toLowerCase();
                String reveiveData = value.replaceAll("ok", "").trim();
                reveiveData = reveiveData.replace(" ", "");
                reveiveData = reveiveData.replace(" ", "");
                reveiveData = reveiveData.replace("\r", "");
                reveiveData = reveiveData.replace("\n", "");
                try {
                    float receive = Float.parseFloat(reveiveData);
                    checkTipDialog.setReceiveDatas(receive);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        }

        /**
         * 阻塞任务执行完后的清理工作
         */
        @Override
        public void onPostExecute(Integer result) {
            if (CONNECT_LOST == result) //connection is lost
                NToast.shortToast(getString(R.string.msg_msg_bt_connect_lost));
            else {
//                NToast.shortToast(getString(R.string.msg_receive_data_stop));
            }
        }
    }


}
